import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/login'
import Home from '@/components/Home/home'
import Welcome from '@/components/Home/welcome'
import User from '@/components/users/user'

Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/login', component: Login },
    {
      path: '/home',
      component: Home,
      redirect: '/welcome',
      children: [
        { path: '/welcome', component: Welcome },
        { path: '/users', component: User }
      ]
    }
  ]
})
// 访问router中的路径之前先执行beforeEach函数
router.beforeEach((to, from, next) => {
  // 如果访问login登陆页面，直接访问
  if (to.path === '/login') return next()
  // 判断是否有token匹配，没有就跳转登陆页面
  const tk = window.sessionStorage.getItem('token')
  if (!tk) return next('/login')
  // 有的话执行下一步
  next()
})

export default router
